import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Form from "react-bootstrap/es/Form";
import Row from "react-bootstrap/es/Row";
import Col from "react-bootstrap/es/Col";
import Checkbox from "react-bootstrap/es/Checkbox";
import ControlLabel from "react-bootstrap/es/ControlLabel";
import FormGroup from "react-bootstrap/es/FormGroup";
import FormControl from "react-bootstrap/es/FormControl";
import DropdownButton from "react-bootstrap/es/DropdownButton";
import ButtonToolbar from "react-bootstrap/es/ButtonToolbar";
import InputGroup from "react-bootstrap/es/InputGroup";
import Button from 'react-bootstrap/es/Button';
import * as httpClient from "../httpclient";
import ProductInfo from "../models/ProductInfo";
import ProductClassTree from "../components/ProductClassTree";
import { Map, fromJS, List } from "immutable";
import { toast, ToastContainer } from "react-toastify";
import events from "../utils/events";
import Unit from "../models/Unit";


class App extends React.PureComponent<any, {
  productInfo: any;
  productClasses: any;
  selectedProductClass: any;
  openProductClassTree: any;
  units: any;
}> {
  private container;
  constructor(props, context) {
    super(props, context);
    this.state = {
      productInfo: Map(new ProductInfo()),
      productClasses: List(),
      selectedProductClass: { text: "默认分类" },
      openProductClassTree: false,
      units: List(),
    }
    httpClient.createSerialNumber("SP")
      .then((serialNumber) => {
        this.updateProductInfo({ "product_code": serialNumber, "product_class_id": 1 })
      })

    httpClient.getProductClasses()
      .then(productClass => {
        this.setState({ productClasses: fromJS(productClass) })
      })

    httpClient.getUnits()
      .then(units => {
        this.setState({ units: List(units) })
      })


    this.saveAndCopyAndNew = this.saveAndCopyAndNew.bind(this);
    this.updateProductClass = this.updateProductClass.bind(this);
    this.onSelectProductClass = this.onSelectProductClass.bind(this)
    this._addSubUnit = this._addSubUnit.bind(this);
  }

  static childContextTypes = {
    addOneAfter: React.PropTypes.func,
    deleteOne: React.PropTypes.func,
    editProduct: React.PropTypes.func,
  }

  getChildContext() {
    return {
    }
  }

  componentDidMount() {
  }

  saveAndNew() {
    httpClient.createProudctInfo(this.state.productInfo.toJS())
  }

  getProductClasses() {

  }

  saveAndCopyAndNew() {
  }

  save() {

  }

  reallyCancel() {

  }

  returnList() {

  }

  createProductClass(parentId, text) {
    httpClient.createProductClass(parentId, text)
      .then(() => {
        this.getProductClasses();
      })
      .catch(() => {
        toast.error("createProductClass");
      })
  }
  updateProductClass(productClass) {
    httpClient.updateProductClass(productClass)
      .catch(() => {
        toast.error("updateProductClass");
      })
  }

  updateProductInfo(mapValue) {
    this.setState({
      productInfo: this.state.productInfo.merge(mapValue)
    })
  }

  deleteNode() {
  }

  onSelectProductClass(productClass) {
    if (!productClass.children) {
      this.setState({
        selectedProductClass: productClass,
        openProductClassTree: false
      });
    }
  }

  _addSubUnit() {
    const productInfo = this.state.productInfo;
    this.setState({ productInfo: productInfo.update("product_subUnits", units => List(units).push({}).toJS()) });
  }

  _delSubUnit(index) {
    const productInfo = this.state.productInfo;
    this.setState({ productInfo: productInfo.update("product_subUnits", units => List(units).delete(index).toJS()) });
  }

  render() {
    const productInfo: ProductInfo = this.state.productInfo.toJS();
    const state = this.state;
    return (
      <div className="main">
        <ToastContainer
          postion="top-center" />
        <ButtonToolbar className="whiteBox" style={{ marginLeft: 0 }}>
          <a id="waitButton" className="button fl processing loadsave" style={{ display: "none" }}>正在保存...</a>
          <Button bsStyle="primary" bsSize="small" className="mr5" onClick={this.saveAndNew.bind(this)}>保存并新增</Button>
          <Button bsSize="small" onClick={this.saveAndCopyAndNew} className="mr5 saveButton">
            <span className="text">保存并复制新增</span>
          </Button>
          <Button bsSize="small" onClick={this.save} className="mr5 saveButton">
            <span className="text">保存</span>
          </Button>
          <Button bsSize="small" onClick={this.reallyCancel} className="mr5 saveButton">
            <span className="text">取消</span>
          </Button>
          <Button bsSize="small" onClick={this.returnList} className="pull-right">商品列表</Button>
        </ButtonToolbar>

        <div className="whiteBox">
          <Row>
            <div className="formTitle">基本信息</div>
            <Col md={8}>
              <Form horizontal componentClass="div">
                {/* <FormGroup bsSize="sm" controlId="strScan">
                  <Col className="font14" componentClass={ControlLabel} sm={2}>
                    条形码
                  </Col>
                  <Col sm={3}>
                    <FormControl type="text" placeholder="选填，扫描或录入条形码" />
                  </Col>
                </FormGroup> */}
                <FormGroup bsSize="sm" controlId="productCode">
                  <Col className="font14" componentClass={ControlLabel} sm={2}>
                    <span className="fontRed">*</span>编号
                  </Col>
                  <Col sm={3}>
                    <FormControl type="text" value={productInfo.product_code || ""} onChange={
                      e => this.updateProductInfo({ product_code: e.target.value })} />
                  </Col>
                </FormGroup>

                <FormGroup bsSize="sm" controlId="productName">
                  <Col className="font14" componentClass={ControlLabel} sm={2}>
                    <span className="fontRed">*</span>名称
                  </Col>
                  <Col sm={3}>
                    <FormControl type="text" value={productInfo.product_name || ""} onChange={
                      e => this.updateProductInfo({ product_name: e.target.value })
                    } />
                  </Col>
                </FormGroup>

                <FormGroup bsSize="sm" controlId="className">
                  <Col className="font14" componentClass={ControlLabel} sm={2}>
                    <span className="fontRed">*</span>分类
                  </Col>
                  <Col sm={3}>
                    <DropdownButton bsSize="sm" componentClass={InputGroup.Button}
                      id="input-dropdown-addon"
                      open={this.state.openProductClassTree}
                      onToggle={(isOpen, event, { source }) => {
                        if (source != "select") {
                          this.setState({ openProductClassTree: isOpen })
                        }
                      }}
                      title={this.state.selectedProductClass.text}>
                      <div style={{ minWidth: "260px" }}>
                        <ProductClassTree
                          nodes={this.state.productClasses}
                          onSelect={this.onSelectProductClass}
                          createProductClass={this.createProductClass}
                          updateProductClass={this.updateProductClass} />
                      </div>
                    </DropdownButton>
                  </Col>
                </FormGroup>

                <FormGroup bsSize="sm" controlId="unit">
                  <Col componentClass={ControlLabel} sm={2}>
                    <span className="fontRed">*</span>单位
                  </Col>
                  <Col sm={3}>
                    <FormControl value="" componentClass="select" placeholder="" >
                      {
                        state.units.map((unit: Unit) => (
                          <option value={unit.unit_name} key={unit.unit_name}>{unit.unit_name}</option>
                        ))
                      }
                    </FormControl>
                  </Col>
                </FormGroup>

                <FormGroup bsSize="sm" controlId="unit">
                  <Col componentClass={ControlLabel} sm={2}>
                    规格
                  </Col>
                  <Col sm={3}>
                    <FormControl type="text" placeholder="选填，如“红色长款" value={productInfo.product_form || ""}
                      onChange={e => this.updateProductInfo({ "product_form": e.target.value })}
                    />
                  </Col>
                </FormGroup>
              </Form>
            </Col>
            <Col md={4}>
              <Row className="uploadProPhoto">
                <Col md={6}>
                  <div className="photoPreview">
                    <img id="productimg" className="pull-right" src="http://cdn.zhsmjxc.com/CDN/Static-webapp/images/proPhoto.png" width="150" height="150" />
                  </div>
                </Col>
                <Col md={6}>
                  <div className="action">
                    <div id="ossfile"></div>
                    <div id="container">
                      <a id="selectfiles" href="javascript:void(0);" className="btn">选择文件</a>
                    </div>
                    <div className="font999">
                      •仅支持jpg、jpeg、png格式<br></br>•图片大小500KB以下,推荐分辨率600*600<br></br>
                      <a href="javascript:;">清空图片</a>
                    </div>
                  </div>
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <div className="formTitle">
              多单位
							<span className="font999" style={{ fontSize: "12px" }}>（多单位时需要把最小度量单位作为基本单位）	</span>
              <a href="javascript:;" className="fr font12">单位设置</a>
            </div>
            <Col md={8}>
              <Form horizontal componentClass="div">
                <FormGroup bsSize="sm" controlId="productCode">
                  <Col className="font14" componentClass={ControlLabel} sm={2}>
                    基本单位
                  </Col>
                  <Col sm={3}>
                    <FormControl componentClass="select" placeholder="" >
                      {
                        state.units.map((unit: Unit) => (
                          <option key={unit.unit_name}>{unit.unit_name}</option>
                        ))
                      }
                    </FormControl>
                  </Col>
                </FormGroup>{
                  productInfo.product_subUnits.map((subUnit, index) =>
                    <FormGroup bsSize="sm" controlId="productCode" key={subUnit.name || index}>
                      <Col className="font14" componentClass={ControlLabel} sm={2}>
                        <span onClick={() => this._delSubUnit(index)} className="operate delLine"></span><span id="unitname">副单位1</span>
                      </Col>
                      <Col sm={3}>
                        <FormControl componentClass="select" placeholder="" >
                          <option>板</option>
                          <option>包</option>
                          <option>个</option>
                          <option>双</option>
                        </FormControl>
                      </Col>
                      <span style={{ float: "left", paddingRight: "15px", lineHeight: "30px" }}>=</span>
                      <FormControl style={{ float: "left", width: '88px' }}></FormControl>
                      <span style={{ float: "left", paddingLeft: "15px", lineHeight: "30px" }}>打</span>
                    </FormGroup>
                  )
                }

                <FormGroup bsSize="sm" controlId="productCode">
                  <Col smOffset={2} sm={3}>
                    <Button className="mr10" bsSize="sm" onClick={this._addSubUnit}>增加单位</Button>
                    <Checkbox bsSize="sm" checked readOnly inline>
                      Checkbox
                    </Checkbox>
                  </Col>
                </FormGroup>
              </Form>
            </Col>

          </Row>

        </div>
      </div >
    );
  }
}


$(function () {
  ReactDOM.render(
    <App></App>, document.getElementById('content')
  );
})